﻿#region License
// Copyright (c) 2009 Shun Chi Guo
// E-Mail:shuncy@gmail.com
// Blog:http://shuncy.cnblogs.com
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

using shun.PAPLib.Request;
using shun.PAPLib.Response;
using System.Text.RegularExpressions;

namespace shun.PAPLib
{
    public class PAPProcess
    {
        #region 网关属性
        /// <summary>
        /// 网关配置信息
        /// </summary>
        public PpgConfig Config = new PpgConfig();
        
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url">PPG网关服务地址</param>
        /// <param name="username">认证用户名</param>
        /// <param name="password">认证密码</param>
        /// <param name="deliveryMethod">投递方法</param>
        /// <param name="sourceReference">业务ID</param>
        /// <param name="PpgNotifyUrl">回调地址</param>
        public PAPProcess(string url, string username, string password, string deliveryMethod, string sourceReference, string PpgNotifyUrl)
        {
            Config.ServiceUrl = url;
            Config.UserName = username;
            Config.Password = password;

            Config.DeliveryMethod = deliveryMethod;
            Config.SourceReference = sourceReference;
            Config.PpgNotifyRequestedTo = PpgNotifyUrl;

            byte[] bt = Encoding.ASCII.GetBytes(Config.UserName + ":" + Config.Password);
            Config.EncPass = "Basic " + Convert.ToBase64String(bt);
        }

        #region 事件处理

        #endregion

        #region 发送接口处理
        /// <summary>
        /// 发送一个请求
        /// </summary>
        /// <param name="request">发送请求的包</param>
        /// <returns></returns>
        public PushResponse SendRequest(PushObject push)
        {
            IRequest pushObj = new Request.PushMessage(push);
            return PushResponse.Convert(ProcHttp(pushObj));
        }
        /// <summary>
        /// 查询指定push_id的请求
        /// </summary>
        /// <param name="push_id">要查询的请求ID</param>
        /// <returns></returns>
        public StatusQueryResponse SendQuery(string push_id)
        {
            IRequest sqm = new StatusQueryMessage(push_id);
            return StatusQueryResponse.Convert(ProcHttp(sqm));
        }
        /// <summary>
        /// 取消一个消息ID
        /// </summary>
        /// <param name="push_id">要取消的消息流水</param>
        /// <returns></returns>
        public CancelResponse CancelMessage(string push_id)
        {
            IRequest cm = new CancelMessage(push_id);
            return CancelResponse.Convert(ProcHttp(cm));
        }

        /// <summary>
        /// CCQMessage
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="Address"></param>
        /// <returns></returns>
        public CCQResponse CCQQuery(string AppID, string Address)
        {
            IRequest ccq = new CCQMessage(AppID, Address);
            return CCQResponse.Convert(ProcHttp(ccq));
        }

        #endregion

        #region Http接口处理
        /// <summary>
        /// 替换掉返回Xml内容的申明信息
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string ReplaceXml(string xml)
        {
            Regex reg = new Regex("<!DOCTYPE((.*)|(.*)\n(.*))>");
            return reg.Replace(xml, "");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rqeuestObj"></param>
        /// <returns></returns>
        private string ProcHttp(IRequest rqeuestObj)
        {
            string ret;
            try
            {
                //Pap请求
                HttpWebRequest papRequest = (HttpWebRequest)HttpWebRequest.Create(Config.ServiceUrl);
                papRequest.Method = "POST";
                papRequest.ContentType = "multipart/related; type=application/xml;boundary=" + IRequest.Boundary;
                papRequest.Headers.Add("Authorization", Config.EncPass);
               
                byte[] papData = rqeuestObj.GetBytes(Config.enc);

                Stream requestStream = papRequest.GetRequestStream();
                requestStream.Write(papData, 0, papData.Length);
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)papRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Config.enc);
                ret = ReplaceXml(sr.ReadToEnd());
                sr.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("执行Http请求出错:"+ex.Message);
            }
            return ret;
        }

        #endregion
    }
}
